﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web;
using Yunzuan.Foundation.Attributes;
using System.Runtime.Serialization;

namespace Yunzuan.Foundation.Entities
{
    //[DataContractAttribute] //加了这个序列化不出来
    public abstract class BaseEntity
    {
        /// <summary>
        /// 修改过的字段
        /// </summary>
        protected HashSet<string> ChangeList = new HashSet<string>();

        /// <summary>
        /// 字段修改通知
        /// </summary>
        /// <typeparam name="T">字段类型</typeparam>
        /// <param name="columnName">字段名称</param>
        /// <param name="newValue">修改后的值</param>
        /// <param name="oldValue">修改前的值</param>
        protected void ChangeNotify<T>(string columnName, T newValue, ref T oldValue)
        {
            if ((newValue == null) || (!newValue.Equals(oldValue)))
            {
                oldValue = newValue;
                if (!this.ChangeList.Contains(columnName))
                {
                    this.ChangeList.Add(columnName);
                }
            }
        }

        /// <summary>
        /// 获取有变动的字段
        /// </summary>
        /// <returns>字段枚举</returns>
        public IEnumerable<ColumnInfo> GetChangedColumn()
        {
            Type t = this.GetType();
            PropertyInfo[] arr = t.GetProperties();
            for (int i = 0; i < arr.Length; i++)
            {
                if (this.ChangeList.Contains(arr[i].Name))
                {
                    ColumnInfo info = new ColumnInfo();
                    info.ColumnName = arr[i].Name;
                    info.SystemType = arr[i].PropertyType;
                    info.ColumnValue = arr[i].GetValue(this, null);

                    object[] attributes = arr[i].GetCustomAttributes(typeof(ColumnAttribute), false);
                    if (attributes.Length > 0 && ((ColumnAttribute)attributes[0]).IsAutoIncrement)
                    {
                        info.IsAutoIncrement = true;
                    }
                    
                    yield return info;
                }
            }
        }
    }
}
